﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ShengYueWorkShop.BLL.PublicHelper
{
    public class WriteLogForFile
    {
        private static string DirName = "SoftLog";
        /// <summary>
        /// 根据日期生成日志文件
        /// </summary>
        /// <returns></returns>
        private static string GetLogPath()
        {
            string FileName = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            return Application.StartupPath + "\\" + DirName + "\\" + FileName;
        }


        /// <summary>
        /// 检查是否存在错误文件日记，如果不存在则重新创建新的文件。
        /// </summary>
        private static void FilePath()
        {
            if (!Directory.Exists(Application.StartupPath + "\\" + DirName))
            {
                Directory.CreateDirectory(Application.StartupPath + "\\" + DirName);
            }
            if (!File.Exists(GetLogPath()))
            {
                File.Create(GetLogPath()).Dispose();
            }
        }

        /// <summary>
        /// 将错误内容写到错误日志当中
        /// </summary>
        /// <param name="datatime">日期</param>
        /// <param name="Text">消息内容</param>
        public static void Write(string datatime, string Text)
        {
            FilePath();
            StreamWriter sw = File.AppendText(GetLogPath());
            string w = "时    间：" + datatime + "\r\n";
            w = w + "内    容：" + Text + "\r\n";
            w = w + "————————————————————————" + "\r\n";
            sw.Write(w);
            sw.Close();
        }
        /// <summary>
        /// 将日志写入到文件中
        /// </summary>
        /// <param name="pStr"></param>
        public static void WirteTxt(string pStr)
        {
            if (pStr.Length > 0)
            {
                pStr += "\r\n";
                FilePath();
                StreamWriter sw = File.AppendText(GetLogPath());
                sw.Write(pStr);
                sw.Close();
            }
        }
    }
}
